
#include "my_net.h"
#include <asm-generic/errno-base.h>
#include <stdio.h>
#include <sys/signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>

int main(int argc, char ** argv) {


    int listenfd, connfd;
    pid_t child_pid;
    void sig_child(int), sig_int(int), web_child(int);

    socklen_t clilen, addrlen;
    struct sockaddr * cliaddr;
    if (argc == 2) {

        listenfd = TcpListen(NULL, argv[1], &addrlen);
    }
    else if (argc == 3){

        listenfd = TcpListen(argv[1], argv[2], &addrlen);
    }
    else {

        printf("usage: serv01 [<host>] <port#>\n");
        return EXIT_FAILURE;
    }
    cliaddr = malloc(addrlen);

    signal(SIGCHLD, sig_child);
    signal(SIGINT, sig_int);

    for (;;) {

      clilen = addrlen;
      if ((connfd = accept(listenfd, cliaddr, &clilen))<0){

          if (errno == EINTR){

              continue;
          }
          else {

            printf("accept error\n");
            return EXIT_FAILURE;
          }
      }
      if ((child_pid = fork()) == 0) {

        close(listenfd);
        web_child(connfd);
        exit(0);
      }
      close(connfd);
    }
    return EXIT_SUCCESS;
}

void sig_int(int no) {

    void pr_cpu_time(void);

    pr_cpu_time();

    exit(0);
}

void sig_child(int no) {

    //printf("%d",waitpid(-1, NULL, WNOHANG));

    waitpid(-1, NULL, WNOHANG);
}
